package com.ykt.service;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.common.utils.Colls;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.Order;
import com.ykt.model.OrderItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单服务
 *
 * @author wing
 * @version 1.0.0
 */
public class OrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);

    private Order orderDao = Order.dao;
    private OrderItem orderItemDao = OrderItem.dao;


    public Order findById(Integer orderId) {
        return orderDao.findById(orderId);
    }

    public List<OrderItem> findOrderItems(Integer orderId) {
        return orderItemDao.findByOrderId(orderId);
    }

    public List<Order> findByOrderPno(String orderPno) {
        return orderDao.findByOrderPno(orderPno);
    }

    public PageData<Order> pageFindByShopId(PageParam<Integer> param) {
        return orderDao.pageFindByShopId(param);
    }

    public PageData<Order> pageFindByUserIdAndStatus(PageParam<Map<String, Object>> param) {
        return orderDao.pageFindByUserIdAndStatus(param);
    }

    public PageData<Order> pageFindByUserIdAndServiceStatus(PageParam<Map<String, Object>> param) {
        return orderDao.pageFindByUserIdAndServiceStatus(param);
    }

    @Before(Tx.class)
    public List<Integer> save(Map<Order, List<OrderItem>> orders) {
        List<Integer> orderIds = new ArrayList<>();

        for (Map.Entry<Order, List<OrderItem>> entry : orders.entrySet()) {
            // 保存订单信息
            entry.getKey().save();

            // 保存订单明细
            int orderId = entry.getKey().getId();
            List<OrderItem> items = entry.getValue();
            if (!Colls.isEmpty(items)) {
                for (OrderItem item : items) {
                    item.set(OrderItem.order_id, orderId);
                    item.save();
                }
            }

            // 返回订单ID
            if (Order.OrderType.PARENT.name().equals(entry.getKey().get(Order.order_type)) ||
                    Order.OrderType.SINGLE.name().equals(entry.getKey().get(Order.order_type))) {
                orderIds.add(0, orderId); // 主订单ID放第一位，供支付使用
            } else {
                orderIds.add(orderId);
            }
        }

        return orderIds;
    }


    @Before(Tx.class)
    public void updateStatus(int orderId, String status) {

        orderDao.set(Order.id, orderId);
        orderDao.set(Order.status, status);
        if (Order.Status.COMPLETED.name().equals(status)) {
            // 当订单已完成则修改订单为待售后状态
            orderDao.set(Order.service_status, Order.ServiceStatus.DELAY_SERVICE.name());
        }
        orderDao.set(Order.updated_time, new Date());

        orderDao.updateByOrderId(orderId, status);
    }
}
